package com.elvish.oda.busin.controller;

import java.util.List;

import org.nutz.lang.Lang;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.elvish.oda.busin.pojo.Permission;
import com.elvish.oda.busin.service.PermissionService;
import com.elvish.oda.common.pojo.Result;
import com.elvish.oda.common.utils.CommonUtil;
import com.elvish.oda.common.utils.ResultUtil;

@RestController
public class PermissionController {

	@Autowired
	private PermissionService permissionService;

	/**
	 * 初始化权限树表格
	 * 
	 * @return
	 */
	@PostMapping(value = "/permission/initPermissionTreeTable")
	public List<Permission> initPermissionTreeTable() {
		List<Permission> permList = permissionService.findAll();
		if (permList != null && permList.size() > 0) {
			List<Permission> treeList = CommonUtil.buildTree(permList, "pid");
			return treeList;
		}
		return null;
	}

	/**
	 * CRUD
	 * 
	 * @param menu
	 */
	@PostMapping(value = "/permission/operPermission/{oper}")
	public Result<Permission> operPermission(Permission permission, @PathVariable("oper") Integer operFlag) {
		Result result = new Result<>();
		try {

			if (operFlag == 1) {
				// 新增
				if (Lang.isEmpty(permission.getId())) {
					permissionService.save(permission);
				}
				// 更新
				else {
					permissionService.update(permission);
				}
			}
			// 删除
			else if (operFlag == 2) {
				permissionService.deleteById(permission.getId());
			}
			result = ResultUtil.success();
		} catch (Exception e) {
			result = ResultUtil.fail(-1, "系统异常");
		}
		return result;
	}

	/**
	 * 给角色分配权限
	 * 
	 * @param roleId
	 *            角色id
	 * @param ids
	 *            权限id
	 * @return
	 */
	@PostMapping(value = "/permission/assignPermissions")
	public Result<Permission> assignPermissions(@RequestParam(value = "roleId") Integer roleId,
			@RequestParam(value = "ids[]") String[] ids) {
		Result result = new Result<>();
		try {
			permissionService.assignPermissions(roleId, ids);
			result = ResultUtil.success();
		} catch (Exception e) {
			result = ResultUtil.fail(-1, "系统异常");
		}
		return result;
	}
}
